package com.lam.dormitory.controller;

import com.lam.dormitory.util.TencentCosUtil;
import com.lam.dormitory.util.ResponseTemplate;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Api(tags = "腾讯云COS")
@RestController
@RequestMapping("/cos")
public class TencentController {

    /**
     * 上传文件
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public ResponseTemplate upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        System.out.println(prefix);
        // 用当前时间作为文件名，防止生成的临时文件重复
        try {
            File file = File.createTempFile(System.currentTimeMillis() + "", prefix);
            multipartFile.transferTo(file);//multipartFile转file
            System.out.println(file);
            TencentCosUtil.uploadFile(file);
            //程序结束时，删除临时文件
            deleteFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseTemplate(200,"上传成功");
    }
    /**
     * 删除
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }

    @PostMapping("/List")
    public ResponseTemplate getBucketObjectList(){
        TencentCosUtil.getBucketObjectList();
        return new ResponseTemplate(200,"查询成功");
    }

    @PostMapping("/download")
    public ResponseTemplate download(){
        TencentCosUtil.downLoadFile();
        return new ResponseTemplate(200,"下载成功");
    }


}
